from interface.widget import Page, scale
from tkinter import ttk, messagebox
from utils.network import request, RespondError
from utils import memory


class LoginPage(Page):

    def content(self, master):
        form_box = ttk.Frame(master)
        form_box.place(**scale(relx=0.5, rely=0.5, width=400, height=200, anchor='center'))

        account_label = ttk.Label(form_box, text='账号')
        account_label.place(**scale(x=0, y=0, width=100, height=40))

        account_entry = ttk.Entry(form_box)
        account_entry.place(**scale(x=100, y=0, width=300, height=40))

        password_label = ttk.Label(form_box, text='密码')
        password_label.place(**scale(x=0, y=60, width=100, height=40))

        password_entry = ttk.Entry(form_box, show='*')
        password_entry.place(**scale(x=100, y=60, width=300, height=40))

        def switch_to_register_page():
            from interface.pages.register import RegisterPage
            self.master.close_page()
            self.master.open_page(RegisterPage(self.master))

        button = ttk.Button(form_box, text='注册', command=switch_to_register_page)
        button.place(**scale(x=0, y=150, width=100, height=50))

        def login_button_method():
            try:
                res = request('/user/login', {
                    'account': account_entry.get(),
                    'password': password_entry.get()
                })
                memory.token = res['token']
                print(res['token'])
                from interface.pages.main import MainPage
                self.master.close_page()
                self.master.open_page(MainPage(self.master))
            except RespondError as e:
                messagebox.showerror('Error', e.res)

        button = ttk.Button(form_box, text='登录', command=login_button_method)
        button.place(**scale(x=120, y=150, width=280, height=50))
